package org.sidora.strata.site;

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.Serializable;
import org.openide.ErrorManager;
import org.openide.util.NbBundle;
import org.openide.util.RequestProcessor;
import org.openide.util.Utilities;
import org.openide.windows.TopComponent;
import org.openide.windows.WindowManager;
import org.sidora.core.Dating;
import org.sidora.core.Phase;


/**
 * Phase Form 
 * @author Enric Tartera, Juan Manuel Gimeno, Roger Masgoret
 * @version 1.0
 */
final class PhaseFormTopComponent extends TopComponent {
    
    private static PhaseFormTopComponent instance;
    private static Phase phase;
    /** path to the icon used by the component and its open action */
//    static final String ICON_PATH = "SET/PATH/TO/ICON/HERE";
    
    private static final String PREFERRED_ID = "PhaseFormTopComponent";
    
    private PhaseFormTopComponent() {
        initComponents();
        setName(NbBundle.getMessage(PhaseFormTopComponent.class, "CTL_PhaseFormTopComponent"));
        setToolTipText(NbBundle.getMessage(PhaseFormTopComponent.class, "HINT_PhaseFormTopComponent"));
//        setIcon(Utilities.loadImage(ICON_PATH, true));
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
    private void initComponents() {
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldName = new javax.swing.JTextField();
        jTextFieldId = new javax.swing.JTextField();
        jTextFieldTaq = new javax.swing.JTextField();
        jTextFieldTpq = new javax.swing.JTextField();

        addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                formFocusGained(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(jLabel1, java.util.ResourceBundle.getBundle("org/sidora/strata/site/Bundle").getString("I:d"));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, java.util.ResourceBundle.getBundle("org/sidora/strata/site/Bundle").getString("Name:"));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, java.util.ResourceBundle.getBundle("org/sidora/strata/site/Bundle").getString("TAQ:"));

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, java.util.ResourceBundle.getBundle("org/sidora/strata/site/Bundle").getString("TPQ:"));

        jTextFieldName.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldNameFocusLost(evt);
            }
        });

        jTextFieldTaq.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldTaqFocusLost(evt);
            }
        });

        jTextFieldTpq.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                jTextFieldTpqFocusLost(evt);
            }
        });

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jLabel2)
                    .add(jLabel1)
                    .add(jLabel3)
                    .add(jLabel4))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jTextFieldId, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 51, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jTextFieldName, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 165, Short.MAX_VALUE)
                    .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING, false)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jTextFieldTpq)
                        .add(org.jdesktop.layout.GroupLayout.LEADING, jTextFieldTaq, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 66, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel1)
                    .add(jTextFieldId, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel2)
                    .add(jTextFieldName, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel3)
                    .add(jTextFieldTaq, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE)
                    .add(jLabel4)
                    .add(jTextFieldTpq, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(31, Short.MAX_VALUE))
        );
    }// </editor-fold>//GEN-END:initComponents
    
    private void jTextFieldTpqFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldTpqFocusLost
        saveAllData();
    }//GEN-LAST:event_jTextFieldTpqFocusLost
    
    private void jTextFieldTaqFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldTaqFocusLost
        saveAllData();
    }//GEN-LAST:event_jTextFieldTaqFocusLost
    
    private void jTextFieldNameFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jTextFieldNameFocusLost
        saveAllData();
    }//GEN-LAST:event_jTextFieldNameFocusLost
    
    private void formFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_formFocusGained
        
    }//GEN-LAST:event_formFocusGained
            
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JTextField jTextFieldId;
    private javax.swing.JTextField jTextFieldName;
    private javax.swing.JTextField jTextFieldTaq;
    private javax.swing.JTextField jTextFieldTpq;
    // End of variables declaration//GEN-END:variables
    
    /**
     * Gets default instance. Do not use directly: reserved for *.settings files only,
     * i.e. deserialization routines; otherwise you could get a non-deserialized instance.
     * To obtain the singleton instance, use {@link findInstance}.
     */
    public static synchronized PhaseFormTopComponent getDefault() {
        if (instance == null) {
            instance = new PhaseFormTopComponent();
        }
        return instance;
    }
    
    /**
     * Obtain the PhaseFormTopComponent instance. Never call {@link #getDefault} directly!
     */
    public static synchronized PhaseFormTopComponent findInstance() {
        TopComponent win = WindowManager.getDefault().findTopComponent(PREFERRED_ID);
        if (win == null) {
            ErrorManager.getDefault().log(ErrorManager.WARNING, "Cannot find PhaseForm component. It will not be located properly in the window system.");
            return getDefault();
        }
        if (win instanceof PhaseFormTopComponent) {
            return (PhaseFormTopComponent)win;
        }
        ErrorManager.getDefault().log(ErrorManager.WARNING, "There seem to be multiple components with the '" + PREFERRED_ID + "' ID. That is a potential source of errors and unexpected behavior.");
        return getDefault();
    }
    
    public int getPersistenceType() {
        return TopComponent.PERSISTENCE_ALWAYS;
    }
    
    public void componentOpened() {
        this.setDisplayName("Phase properties");
        if (this.phase != null){
            fillSiteFields();
        }else{
            emptySiteFields();
        }
    }
    
    public void componentClosed() {
        saveAllData();
    }
    
    /** replaces this in object stream */
    public Object writeReplace() {
        return new ResolvableHelper();
    }
    
    protected String preferredID() {
        return PREFERRED_ID;
    }
    
    final static class ResolvableHelper implements Serializable {
        private static final long serialVersionUID = 1L;
        public Object readResolve() {
            return PhaseFormTopComponent.getDefault();
        }
    }
    
    public static Phase getPhase() {
        return phase;
    }
    
    public static void setPhase(Phase aPhase) {
        phase = aPhase;
    }
    
    
    public void fillSiteFields(){
        if (this.phase != null){
            jTextFieldId.setText(phase.getId());
            jTextFieldName.setText(phase.getName());
            jTextFieldTaq.setText(phase.getDating().getTaq().toString());
            jTextFieldTpq.setText(phase.getDating().getTpq().toString());
        }else{
            emptySiteFields();
        }
    }
    
    public void emptySiteFields(){
        jTextFieldId.setText("");
        jTextFieldName.setText("");
        jTextFieldTaq.setText("");
        jTextFieldTpq.setText("");
        this.phase = null;
    }
    
    public void saveAllData(){
        if (this.phase != null){
            int i;
            
            Phase phase = this.phase;
            Dating dating = new Dating();
            
            try{
                dating.setTaq(Integer.parseInt(jTextFieldTaq.getText()));
            }catch(Exception e){
                dating.setTaq(0);
            }
            
            try{
                dating.setTpq(Integer.parseInt(jTextFieldTpq.getText()));
            }catch(Exception e){
                dating.setTpq(0);
            }
            
            phase.setName(jTextFieldName.getText());
            phase.setDating(dating);
            
            Phase.Inventory.setObject(phase);
            
            this.phase = phase;
        }
    }
    
}
